package com.mxw.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mxw.entity.Resource;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class WechatMpService {
    private static final Logger logger = LoggerFactory.getLogger(WechatMpService.class);

    @Value("${wechat.mp.appid}")
    private String appId;

    @Value("${wechat.mp.secret}")
    private String secret;

    private static final String PROMPT_TEMPLATE = "重写3个自然段。改写要求：文案必须健康正能量，保持原文的核心观点和主题，改变语句结构和措辞，不要抄袭原文，增加细节描写，使语言更丰富，调整结构增强逻辑性，改变文体使语言更生动流畅。第一段以大家好，今天我给大家推荐为开头的推荐文案，字数在300字以上，第二段承上启下，扩展第一段的内容，第三段写总结。每个自然段300字左右。\n\n原文：%s";

    @Autowired
    DeepSeekService deepSeekService;

    /**
     * 格式化文案内容
     *
     * @param content     原始文案内容
     * @param resourceUrl 资源链接地址
     * @return 格式化后的文案内容
     */
    private String formatArticleContent(String content, String resourceUrl) {
        // 去除段落标记（如"**第一段：推荐开场**"）
        content = content.replaceAll("\\*\\*.*?\\*\\*\\s*", "");

        // 分割段落
        String[] paragraphs = content.split("\n\n");
        StringBuilder formattedContent = new StringBuilder();

        formattedContent.append("<section style=\"color: rgb(62, 62, 62); font-size: 16px; white-space: normal; transform: scale(1); visibility: visible;\"><p style=\"text-align: center; vertical-align: inherit; letter-spacing: 5px; visibility: visible;\"><span style=\"color: rgb(255, 169, 0); font-size: 35px; visibility: visible;\"><span leaf=\"\" style=\"visibility: visible;\">程序员的分享</span></span></p><p style=\"text-align: center; vertical-align: inherit; letter-spacing: 2.5px; margin-top: -5px; transform: scale(1); padding-right: 30px; padding-left: 30px; max-width: 100%; box-sizing: border-box; line-height: 1.6; margin-bottom: 0px; color: rgb(62, 62, 62); font-size: 16px; white-space: normal; background-color: rgb(255, 255, 255); overflow-wrap: break-word !important; visibility: visible;\"><span style=\"font-size: 15px; visibility: visible;\"><strong style=\"visibility: visible;\"><span style=\"font-size: 15px; caret-color: rgb(255, 127, 90); color: rgba(0, 0, 0, 0.5); letter-spacing: 0.544px; text-align: justify; font-family: system-ui, -apple-system, BlinkMacSystemFont, Arial, sans-serif; display: inline !important; visibility: visible;\"><span leaf=\"\" style=\"visibility: visible;\"><br style=\"visibility: visible;\"></span></span></strong></span></p></section>");

        formattedContent.append("<h2 style='color: #1E90FF; font-size: 20px; margin-bottom: 15px;'>资源介绍</h2>\n");

        for (int i = 0; i < paragraphs.length; i++) {
            String paragraph = paragraphs[i].trim();
            // 添加段落内容样式
            formattedContent.append("<p style='font-size: 16px; line-height: 1.8; color: #333; margin-bottom: 20px; text-align: justify;'>")
                    .append(paragraph)
                    .append("</p>\n\n");
        }

        // 添加资源链接
        formattedContent.append("<div style='margin-top: 30px; padding: 20px; background: linear-gradient(to right, #f8f9fa, #e9ecef); border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05);'>")
                .append("<h2 style='color: #1E90FF; font-size: 20px; margin-bottom: 15px; font-weight: 600;'>资源链接</h2>\n")
                .append("<p style='margin: 0 0 12px 0; color: #666; font-size: 15px;'>长按复制到浏览器打开：</p>")
                .append("<div style='margin: 10px 0; padding: 12px 15px; background-color: #fff; border: 1px solid #e0e0e0; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.05);'>")
                .append("<span style='color: #1E90FF; font-size: 16px; word-break: break-all; line-height: 1.6; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;'>")
                .append(resourceUrl)
                .append("</span>")
                .append("</div>")
                .append("<p style='margin: 12px 0 0 0; color: #888; font-size: 13px;'>提示：复制链接后，请使用本地浏览器打开</p>")
                .append("</div>\n\n");

        formattedContent.append("<h2 style='color: #1E90FF; font-size: 20px; margin-bottom: 15px;'>声明和投稿</h2>\n")
                .append("<p style='margin: 0; color: #666;'>1、本频道所有资源文章出自互联网收集整理，本站不参与制作，如果侵犯了您的合法权益，请联系本站我们会及时删除。</p>")
                .append("<p style='margin: 0; color: #666;'>2、本频道资源仅供研究、学习交流之用，若使用商业用途，请购买正版授权，否则产生的一切后果将由下载用户自行承担。</p>")
                .append("<p style='margin: 0; color: #666;'>3、如果你有有趣的东西想要分享，可以私信我，投稿的内容不能涉及政治和触犯法律等等，尽量积极向上的内容哈。</p>");

        return formattedContent.toString();
    }

    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .build();


    public void testCreateDraft(List<Resource> resources) {
        try {
            // 配置微信公众号信息
            WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
            config.setAppId(appId);
            config.setSecret(secret);

            // 创建微信服务实例
            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(config);

            // 创建草稿文章列表
            List<Map<String, Object>> articles = new ArrayList<>();

            for (Resource resource : resources) {
                // 获取AI重写后的内容
                String originalText = resource.getContent();
                String prompt = String.format(PROMPT_TEMPLATE, originalText);
                String response = deepSeekService.sendRequest(prompt);
                logger.info("AI响应结果：{}", response);

                // 获取资源链接地址
                String resourceUrl = String.format("https://milkcode.top/resource/id/%s", resource.getId());

                // 格式化文案内容
                String formattedContent = formatArticleContent(response, resourceUrl);
                String thumbMediaId = "";
                // 处理图片
                try {
                    // 从Resource获取图片URL
                    String imageUrl = resource.getCoverUrl();
                    if (imageUrl != null && !imageUrl.isEmpty()) {
                        File tempFile = null;
                        try {
                            // 创建临时文件
                            tempFile = File.createTempFile("wx_image_", ".jpg");
                            // 下载图片
                            Request request = new Request.Builder()
                                    .url(imageUrl)
                                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                                    .build();

                            try (Response imgResponse = client.newCall(request).execute()) {
                                if (!imgResponse.isSuccessful()) {
                                    throw new IOException("下载图片失败: " + imgResponse.code());
                                }

                                // 将图片保存到临时文件
                                try (InputStream inputStream = imgResponse.body().byteStream();
                                     FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                                    byte[] buffer = new byte[4096];
                                    int bytesRead;
                                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                                        outputStream.write(buffer, 0, bytesRead);
                                    }
                                }

                                // 上传图片到微信
                                WxMpMaterial material = new WxMpMaterial();
                                material.setFile(tempFile);
                                material.setName(tempFile.getName());

                                logger.info("开始上传图片到微信...");
                                WxMpMaterialUploadResult uploadResult = wxMpService.getMaterialService().materialFileUpload(
                                        WxConsts.MediaFileType.IMAGE,
                                        material
                                );

                                if (uploadResult != null) {
                                    thumbMediaId = uploadResult.getMediaId();
                                    logger.info("图片上传成功，media_id: {}", uploadResult.getMediaId());
                                    // 创建文章
                                    Map<String, Object> article = new HashMap<>();
                                    article.put("title", resource.getTitle());
                                    article.put("author", "milkcode");
                                    if (resource.getContent().length()>50){
                                        article.put("digest", resource.getContent().substring(0, 50));
                                    }else {
                                        article.put("digest", resource.getContent());
                                    }
                                    article.put("content", formattedContent);
                                    article.put("thumb_media_id", thumbMediaId);
                                    article.put("show_cover_pic", 1);
                                    article.put("need_open_comment", 1);
                                    article.put("only_fans_can_comment", 0);
                                    article.put("need_open_reprint", 0);
                                    articles.add(article);
                                } else {
                                    logger.error("图片上传失败，返回结果为空");
                                }
                            }
                        } catch (Exception e) {
                            logger.error("处理图片时发生错误", e);
                        } finally {
                            if (tempFile != null && !tempFile.delete()) {
                                logger.error("临时文件删除失败");
                            }
                        }
                    } else {
                        logger.error("资源图片URL为空");
                    }

                } catch (Exception e) {
                    logger.error("处理图片时发生错误: " + e.getMessage());
                }
            }

            // 创建草稿
            Map<String, Object> draftData = new HashMap<>();
            draftData.put("articles", articles);
            draftData.put("need_open_comment", 1);
            draftData.put("only_fans_can_comment", 0);
            draftData.put("need_open_reprint", 0);

            // 调用接口创建草稿
            logger.info("开始创建草稿...");
            String result = wxMpService.post("https://api.weixin.qq.com/cgi-bin/draft/add?need_open_comment=1&only_fans_can_comment=0&need_open_reprint=0", JSON.toJSONString(draftData));
            logger.debug("草稿创建接口返回: {}", result);

            if (result == null) {
                throw new RuntimeException("创建草稿失败，返回结果为空");
            }

            JSONObject jsonResult = JSON.parseObject(result);
            if (jsonResult == null) {
                throw new RuntimeException("解析返回结果失败");
            }

            Integer errcode = Optional.ofNullable(jsonResult.getInteger("errcode")).orElse(0);

            if (errcode == 0) {
                logger.info("草稿创建成功，media_id: {}", jsonResult.getString("media_id"));
            } else {
                logger.error("创建草稿失败: {}", jsonResult.getString("errmsg"));
                return;
            }

            // 获取草稿列表
            logger.info("开始获取草稿列表...");
            String draftListResult = wxMpService.post("https://api.weixin.qq.com/cgi-bin/draft/batchget", "{\"offset\":0,\"count\":20,\"no_content\":0}");
            logger.debug("草稿列表接口返回: {}", draftListResult);

            if (draftListResult == null) {
                throw new RuntimeException("获取草稿列表失败，返回结果为空");
            }

            JSONObject jsonResultAll = JSON.parseObject(draftListResult);
            if (jsonResultAll == null) {
                throw new RuntimeException("解析返回结果失败");
            }

            Integer errcodeAll = Optional.ofNullable(jsonResultAll.getInteger("errcode")).orElse(0);
            if (errcodeAll != 0) {
                throw new RuntimeException("获取草稿列表失败: " + jsonResultAll.getString("errmsg"));
            }

            // 获取最新的草稿media_id
            JSONArray items = jsonResultAll.getJSONArray("item");
            if (items == null || items.isEmpty()) {
                throw new RuntimeException("没有找到草稿");
            }

            String mediaId = items.getJSONObject(0).getString("media_id");
            logger.info("获取到最新的草稿media_id: {}", mediaId);

            // 群发文章
            logger.info("开始群发文章...");
            Map<String, Object> massSendData = new HashMap<>();
            massSendData.put("filter", new HashMap<String, Object>() {{
                put("is_to_all", true);
            }});
            massSendData.put("mpnews", new HashMap<String, Object>() {{
                put("media_id", mediaId);
            }});
            massSendData.put("msgtype", "mpnews");
            massSendData.put("send_ignore_reprint", 0); // 0表示不忽略原创声明

            String massSendResult = wxMpService.post("https://api.weixin.qq.com/cgi-bin/message/mass/sendall", JSON.toJSONString(massSendData));
            logger.debug("群发接口返回: {}", massSendResult);

            if (massSendResult == null) {
                throw new RuntimeException("群发文章失败，返回结果为空");
            }

            JSONObject massSendJsonResult = JSON.parseObject(massSendResult);
            if (massSendJsonResult == null) {
                throw new RuntimeException("解析群发返回结果失败");
            }

            errcode = Optional.ofNullable(massSendJsonResult.getInteger("errcode")).orElse(0);
            if (errcode == 0) {
                String msgId = massSendJsonResult.getString("msg_id");
                logger.info("群发文章成功，msg_id: {}", msgId);
            } else {
                logger.error("群发文章失败: {}", massSendJsonResult.getString("errmsg"));
            }

        } catch (Exception e) {
            logger.error("创建草稿失败", e);
        }
    }


}
